package org.halk.myutils;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import lombok.extern.slf4j.Slf4j;


/**
 * hutool中SM国密加密
 *
 * @ClassName SMUtils
 * @Description hutool中SM国密加密
 * @Author arvin
 * @Version 1.0
 * @Date 2021-06-30 17:32:40
 */
@Slf4j
public class SMUtils {
    /**
     * 默认的 sm4加密key
     */
    public static final String DEFAULT_SM4_SECRET_KEY = "Swk1tstd3cUnkLXu";


    /**
     * SM4加密
     * @param data 需要加密的字符串
     * @param secretKey 需要加密的字符串
     * @return 返回加密后的字符串
     */
    public static String toSM4Str(String data,String secretKey) {
        SymmetricCrypto sm4 = SmUtil.sm4(secretKey.getBytes(CharsetUtil.CHARSET_UTF_8));
        return sm4.encryptHex(data, CharsetUtil.CHARSET_UTF_8).toUpperCase();
    }

    /**
     * 调用的SM4加密方法
     * @param data
     * @return
     */
    public static String toSM4Str(String data) {
        return toSM4Str(data,DEFAULT_SM4_SECRET_KEY);
    }

    /**
     * SM4解密
     * @param data 需要加密的字符串
     * @param secretKey 需要加密的字符串
     * @return 返回加密后的字符串
     */
    public static String parseSM4Str(String data,String secretKey) {
        SymmetricCrypto sm4 = SmUtil.sm4(secretKey.getBytes(CharsetUtil.CHARSET_UTF_8));
        return sm4.decryptStr(data, CharsetUtil.CHARSET_UTF_8);
    }

    /**
     * 调用的SM4解密方法
     * @param data
     * @return
     */
    public static String parseSM4Str(String data) {
        return parseSM4Str(data,DEFAULT_SM4_SECRET_KEY);
    }

    public static void main(String[] args) throws Exception {

        String secretKey = DEFAULT_SM4_SECRET_KEY;
        String name = toSM4Str("xiaoming", secretKey);
        log.info(name);

        String s = parseSM4Str(name, secretKey);
        log.info(s);
//        log.info(RandomUtil.randomString(16));
//        toSM2Str("haobb");
//        SM4 sm4 = new SM4();
//        String encodeStr =  sm4.encode("xiaoming",DEFAULT_SM4_SECRET_KEY);
//        System.out.println("+++++++++2"+encodeStr);
//        String decodeStr =  sm4.decode("a7bff9cddac07133e74227ed418a796d",DEFAULT_SM4_SECRET_KEY);
//        System.out.println(decodeStr);

    }





}
